package io.github.loserYa.utils;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 获取不同数据源的 rabbit template
 *
 * @author loser
 * @date 2024/4/25
 */
public class RabbitMqUtil implements ApplicationContextAware {

    private static final Map<String, RabbitTemplate> map = new ConcurrentHashMap<>();
    private static ApplicationContext context;
    private static Environment environment;
    private static String exchange;
    private static String logPre;
    private static Integer size;

    public RabbitMqUtil(Environment environment) {
        RabbitMqUtil.environment = environment;
    }

    public static String getLogPre() {

        if (!StringUtils.isEmpty(logPre)) {
            return logPre;
        }
        synchronized (RabbitMqUtil.class) {
            if (!StringUtils.isEmpty(logPre)) {
                return logPre;
            }
            logPre = environment.getProperty("rabbitmq.log.logPre");
        }
        return logPre;

    }

    public static int getSize() {
        if (Objects.nonNull(size)) {
            return size;
        }
        synchronized (RabbitMqUtil.class) {
            if (Objects.nonNull(size)) {
                return size;
            }
            Integer config = environment.getProperty("rabbitmq.log.size", Integer.class);
            if (Objects.isNull(config)) {
                size = 200;
            } else {
                size = config;
            }
        }
        return size;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static String getLogExchange() {

        if (!StringUtils.isEmpty(exchange)) {
            return exchange;
        }
        synchronized (RabbitMqUtil.class) {
            if (!StringUtils.isEmpty(exchange)) {
                return exchange;
            }
            exchange = environment.getProperty("rabbitmq.log.exchange");
        }
        return exchange;

    }

    public static RabbitTemplate get(String pre) {

        String name = pre + "RabbitTemplate";
        RabbitTemplate rabbitTemplate = map.get(name);

        if (Objects.nonNull(rabbitTemplate)) {
            return rabbitTemplate;
        }
        synchronized (RabbitMqUtil.class) {
            rabbitTemplate = map.get(name);
            if (Objects.nonNull(rabbitTemplate)) {
                return rabbitTemplate;
            }
            rabbitTemplate = context.getBean(name, RabbitTemplate.class);
            map.put(name, rabbitTemplate);
        }
        return rabbitTemplate;

    }


}
